
const router = require( 'koa-router' )();
const path = require( 'path' );
const redisUtils = require('../utils/redis_utils');
const cacheKeyUtils = require('../utils/cache_key_utils');
const userData = require( '../models/user_data' );
// const dataCategory = require( '../models/data_category' );

const headers = { 'Content-Type': 'application/json', 'Encoding': 'utf8' };

const resetMetadata = async function ( ctx, next ) {

    try {

        let userId = ctx.request.cookies.userId;
        let uid = ctx.request.body.uid;
        let metadata = ctx.request.body.metadata;

        let userdata = await userData.getByUid(uid);
        if (userdata && userdata[0] && userdata[0].user_id !== userId) {
            return ctx.body = { code: 602, msg: '无更新权限' };
        }

        let result = await userData.updateMetadata(uid, metadata);

        if ( result ) {

            let cacheKey = cacheKeyUtils.genUserDataKey(uid);
            let success = redisUtils.del(cacheKey);
            if (success === 0) {
                console.error('清除 redis key 失败');
            }
            return ctx.body = { code: 0 };

        }

        return ctx.body = { code: 706, msg: '操作失败' };

    } catch (e) {

        return ctx.body = { code: 706, msg: '操作失败' };

    }

}

// const getDataAdministrativeRegion = async function() {
//
//     try {
//
//         let result = await dataCategory.getAll();
//
//         if (result) {
//             return ctx.body = { code: 0, data: result.rows };
//         }
//
//         return ctx.body = { code: 706, msg: '操作失败' };
//
//     } catch (e) {
//
//         console.error(e);
//         return ctx.body = { code: 706, msg: '操作失败' };
//
//     }
//
// }


router.post( '/:dataUid/metadata/update', resetMetadata );
// router.post( '/administrative_region/all', getDataAdministrativeRegion );

module.exports = router;
